
<template>
  <div class="worker-repair-center">
    <!-- 公告部分 -->
    <el-collapse v-model="historyAnnouncement" class="announcement-section">
      <el-collapse-item name="1">
        <template #title>
          <div class="announcement-header">
            <i class="fa fa-bullhorn" aria-hidden="true"></i>&nbsp;系统公告
          </div>
        </template>
        <el-alert v-for="item in pageAnnouncementList" :key="item.id" :title="item.title"
          :type="item.alertType || 'info'" :closable="false" class="announcement-item">
          <div class="layout">
            <div class="content">{{ item.content }}</div>
            <div class="about">
              <div class="issueAuthor">
                <i class="fa fa-user-circle-o"></i>&nbsp;{{ item.issueAuthor }}
              </div>
              <div class="issueTime">
                <span><i class="fa fa-clock-o"
                    aria-hidden="true"></i>&nbsp;{{ item.issueTime }}</span>
              </div>
            </div>
          </div>
        </el-alert>
        <div class="pagination">
          <el-pagination @size-change="val => announcementPagination.pageSize = val"
            @current-change="val => announcementPagination.currentPage = val"
            :current-page="announcementPagination.currentPage"
            :pager-count="announcementPagination.pagerCount"
            :page-sizes="announcementPagination.pageSizes"
            :page-size="announcementPagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="announcementPagination.total"
            background>
          </el-pagination>
        </div>
      </el-collapse-item>
    </el-collapse>
    
    <!-- 报修订单列表部分 -->
    <div class='repairCenter_container resize-observer-fix'>
      <el-card class="table-card">
        <template #header>
          <div class="card-header">
            <span class="title">待接单列表</span>
            <div class="header-actions">
              <el-tooltip content="刷新数据" placement="top">
                <el-button circle @click="queryUserOrderRecord" type="primary" size="small">
                  <i class="fa fa-refresh"></i>
                </el-button>
              </el-tooltip>
            </div>
          </div>
        </template>
        
        <el-table
          class="order-table resize-observer-fix"
          :data="tableData.slice((pagination.currentPage-1)*pagination.pageSize, pagination.currentPage*pagination.pageSize)"
          border :header-cell-style="{background:'#f5f7fa',color:'#333'}"
          :default-sort="{prop: 'repairDate', order: 'descending'}" @filter-change="filterTagTable"
          style="width: 100%">
          <el-table-column type="index" align="center" width="60" :index="tableIndex">
          </el-table-column>
          <el-table-column highlight-current-row align="center" prop="orderId" label="单号">
          </el-table-column>
          <el-table-column align="center" prop="repairContent" label="报修问题">
            <template #default="scope">
              <div class="repair-content">{{ scope.row.repairContent }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="repairTypeEntity.typeValue" label="报修类型">
            <template #default="scope">
              <el-tag size="small" effect="plain" type="info">{{ scope.row.repairTypeEntity.typeValue }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="repairStatusEntity.statusValue" label="报修状态"
            :filters="repairStatusFilters" filter-placement="bottom-end" column-key="aStatus">
            <template #default="scope">
              <el-tag :type="repairStatusStyle(scope.row.statusCode)" effect="light"
                disable-transitions class="status-tag">
                {{scope.row.repairStatusEntity.statusValue}}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="repairDate" label="报修时间" width="200" sortable>
          </el-table-column>
          <el-table-column align="center" label="图片资料" width="180">
            <template #default="scope">
              <div class="resize-observer-fix image-container">
                <el-image 
                  class="resize-observer-fix thumbnail" 
                  v-for="url in scope.row.imgUrl"
                  :key="url" 
                  :src="url" 
                  fit="cover" 
                  :preview-src-list="scope.row.imgUrl">
                </el-image>
                <div v-if="!scope.row.imgUrl || scope.row.imgUrl.length === 0" class="no-images">
                  无图片
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="120">
            <template #default="scope">
              <el-button type="primary" size="small" class="accept-btn" @click="acceptOrder(scope.row)">
                <i class="fa fa-check-circle"></i> 接单
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination @size-change="val=>pagination.pageSize = val"
            @current-change="val=>pagination.currentPage = val" :current-page="pagination.currentPage"
            :pager-count="pagination.pagerCount" :page-sizes="pagination.pageSizes"
            :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total" background>
          </el-pagination>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { useMainStore } from '@/js/store.js'
import { imgUrlAddress, repairStatusStyle } from '@/js/public.js'
import nProgress from 'nprogress';
import { ElMessage } from 'element-plus'
var that;
export default {
  data () {
    //这里存放数据
    return {
      store: useMainStore(),
      historyAnnouncement: '1',
      announcementList: [],
      announcementPagination: {
        pageSize: 3,
        pageSizes: [3, 10, 100, 200],
        pagerCount: 5,
        currentPage: 1,
        total: 0
      },
      tableData: [],
      tableDataF: [],
      pagination: {
        pageSize: 10,
        pageSizes: [10, 50, 100, 200],
        pagerCount: 5,
        currentPage: 1,
        total: 0,
      },
      queryList: {
        aStatus: []
      },
      repairStatusStyle,
      // 添加ElMessage使其在this中可用
      ElMessage: ElMessage
    }
  },
  //监听属性 类似于data概念
  computed: {
    repairStatusFilters () {
      let filters = new Array();
      this.store.repairStatus?.forEach((item, idx) => {
        let obj = {
          text: item.statusValue,
          value: item.statusValue
        }
        filters.push(obj);
      })
      return filters;
    },
    'pageAnnouncementList': function () {
      return this.announcementList.slice(
        (this.announcementPagination.currentPage - 1) * this.announcementPagination.pageSize, this.announcementPagination.currentPage * this.announcementPagination.pageSize
      )
    },
  },
  //监控data中的数据变化
  watch: {
    tableData: function (val) {
      this.pagination.total = val.length;
    }
  },
  //方法集合
  methods: {
    /**
     * @description: 后端拉取所有公告信息
     * @param {*}
     * @return {*}
     */
    async execPullAllAnnouncement () {
      try {
        console.log("开始获取公告信息");
        // 确保API路径正确，不添加多余前缀
        const result = await (await this.axios.get('/userHome/pullAllAnnouncement')).data
        console.log("公告信息响应:", result);
        
        if (result.code === 43000) {
          this.announcementList = result.data || []
          this.announcementList.sort(function (a, b) {
            return b.issueTime < a.issueTime ? -1 : 1
          })
          this.announcementPagination.total = this.announcementList.length
        } else if (result.code === 43001) {
          this.announcementList = [];
          this.announcementPagination.total = 0;
          this.ElMessage.warning(result.msg || "暂无公告")
        }
      } catch (error) {
        console.error("获取公告失败:", error);
        // 失败时使用空数组
        this.announcementList = [];
        this.announcementPagination.total = 0;
        // 显示友好的错误信息
        this.ElMessage.warning("获取公告信息失败，请稍后再试");
      }
    },
    acceptOrder (row) {
      console.log("开始接单，订单数据:", row);
      let data = JSON.parse(JSON.stringify(row));
      
      // 确保imgUrl存在并正确处理
      if (data.imgUrl && Array.isArray(data.imgUrl)) {
        console.log("处理图片数据，原始图片URL:", data.imgUrl);
        data.imgUrl = JSON.stringify(data.imgUrl);
      } else if (!data.imgUrl) {
        console.log("图片URL为空，设置为空数组");
        data.imgUrl = JSON.stringify([]);
      } else if (typeof data.imgUrl === 'string') {
        // 如果已经是字符串，确保它是有效的JSON
        try {
          JSON.parse(data.imgUrl); // 验证是否为有效的JSON
        } catch (e) {
          console.error("imgUrl不是有效的JSON，重置为空数组", data.imgUrl);
          data.imgUrl = JSON.stringify([]);
        }
      }
      
      console.log("发送接单请求，处理后的数据:", data);
      
      this.axios.post("/workerHome/acceptOrder", data)
        .then(res => {
          console.log("接单响应:", res.data);
          if (res.data.code == 43000) {
            this.ElMessage.success(res.data.msg);
            this.tableData.some((item, index) => {
              if (item.orderId == row.orderId) {
                this.tableData.splice(index, 1);
                return true;
              }
            })
          } else {
            this.ElMessage.error(res.data.msg);
          }
        })
        .catch(err => {
          console.error("接单请求失败:", err);
          this.ElMessage.error("接单失败，请检查网络或联系管理员");
        });
    },
    tableIndex (index) {
      return (index + 1) + (this.pagination.currentPage - 1) * this.pagination.pageSize;
    },
    filterTagTable (filters) {
      console.log("应用过滤器:", filters);
      
      // 初始化查询列表
      this.queryList.aStatus = filters.aStatus || [];
      
      try {
        if (filters.aStatus && Array.isArray(filters.aStatus) && filters.aStatus.length > 0) {
          console.log("根据状态过滤:", filters.aStatus);
          this.tableDataF = this.tableData.filter((element) => {
            // 确保元素和状态实体存在
            if (element && element.repairStatusEntity && element.repairStatusEntity.statusValue) {
              return filters.aStatus.includes(element.repairStatusEntity.statusValue);
            }
            return false;
          });
        } else {
          // 如果没有过滤条件，显示所有数据
          console.log("没有应用过滤条件，显示所有数据");
          this.tableDataF = [...this.tableData];
        }
      } catch (error) {
        console.error("过滤表格时出错:", error);
        // 出错时显示所有数据
        this.tableDataF = [...this.tableData];
        this.ElMessage.error("过滤数据时发生错误");
      }
    },
    queryUserOrderRecord () {
      nProgress.start()
      this.axios.get("/workerHome/queryNewOrders").then(res => {
        console.log("获取新订单数据:", res.data);
        
        if (res.data && res.data.code === 43000) {
          this.tableData = res.data.data ? res.data.data.reverse() : [];
          
          // 安全处理每个订单的图片URL
          this.tableData.forEach((item, idx) => {
            try {
              if (item && item.imgUrl) {
                this.tableData[idx].imgUrl = imgUrlAddress(item.imgUrl);
              } else {
                this.tableData[idx].imgUrl = [];
              }
            } catch (error) {
              console.error(`处理订单${item.orderId}的图片URL时出错:`, error);
              this.tableData[idx].imgUrl = [];
            }
          });
          
          console.log("处理后的订单数据:", this.tableData);
        } else {
          console.error("获取新订单失败:", res.data);
          this.tableData = [];
          this.ElMessage.error(res.data?.msg || "获取新订单失败");
        }
        
        nProgress.done();
      }).catch(err => {
        console.error("获取新订单请求失败:", err);
        this.tableData = [];
        this.ElMessage.error("获取新订单失败，请检查网络或联系管理员");
        nProgress.done();
      });
    },
    filterStatusVal (value, row) {
      return row.statusVal == value;
    },
    getRepairStatus() {
      // 如果store中已有数据则直接返回
      if (this.store.repairStatus && this.store.repairStatus.length > 0) {
        console.log("从store获取到报修状态数据:", this.store.repairStatus);
        return;
      }
      
      console.log("开始获取报修状态数据");
      this.axios.get("/userHome/repairStatus").then(res => {
        console.log("报修状态API响应:", res);
        
        if (res.data && res.data.code === 43000 && res.data.data) {
          console.log("获取到报修状态数据:", res.data.data);
        this.store.repairStatus = res.data.data;
        } else {
          console.error("报修状态数据获取失败或为空", res.data);
          // 设置静态数据
          this.store.repairStatus = [
            { statusCode: 1, statusValue: "待接单" },
            { statusCode: 2, statusValue: "已接单" },
            { statusCode: 3, statusValue: "维修中" },
            { statusCode: 4, statusValue: "维修完成" },
            { statusCode: 5, statusValue: "已拒绝" }
          ];
        }
      }).catch(err => {
        console.error("获取报修状态数据出错:", err);
        // 设置静态数据
        this.store.repairStatus = [
          { statusCode: 1, statusValue: "待接单" },
          { statusCode: 2, statusValue: "已接单" },
          { statusCode: 3, statusValue: "维修中" },
          { statusCode: 4, statusValue: "维修完成" },
          { statusCode: 5, statusValue: "已拒绝" }
        ];
      });
    },
    
    getRepairType() {
      // 修改：检查数组长度而不是仅检查存在性
      if (this.store.repairType && this.store.repairType.length > 0) return;
      
      console.log("开始获取报修类型数据");
      this.axios.get("/userHome/repairType").then(res => {
        if (res.data && res.data.data) {
          console.log("获取到报修类型数据:", res.data.data);
        this.store.repairType = res.data.data;
        } else {
          console.error("报修类型数据获取失败或为空");
        }
      }).catch(err => {
        console.error("获取报修类型数据出错:", err);
      });
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.queryUserOrderRecord();
    this.getRepairStatus(); // 确保调用获取报修状态方法
    this.getRepairType();
    that = this;
    this.execPullAllAnnouncement()
  },
  
  // 添加立即初始化方法
  mounted() {
    // 确保立即有数据可用
    if (!this.store.repairStatus || this.store.repairStatus.length === 0) {
      console.log("立即初始化报修状态数据");
      this.store.repairStatus = [
        { statusCode: 1, statusValue: "待接单" },
        { statusCode: 2, statusValue: "已接单" },
        { statusCode: 3, statusValue: "维修中" },
        { statusCode: 4, statusValue: "维修完成" },
        { statusCode: 5, statusValue: "已拒绝" }
      ];
    }
  },

  beforeDestroy() {
    // 清理可能存在的ResizeObserver
    if (window.observer) {
      try {
        window.observer.disconnect();
      } catch (e) {
        console.log('清理observer时发生错误:', e);
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.worker-repair-center {
  width: 100%;
  position: relative;
  
  // 公告部分样式
  .announcement-section {
    margin-bottom: 20px;
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s ease;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    
    .announcement-header {
      font-size: 16px;
      font-weight: bold;
      display: flex;
      align-items: center;
      color: #2c3e50;
      
      i {
        color: #e6a23c;
        font-size: 18px;
        margin-right: 6px;
      }
    }
    
    .announcement-item {
      margin-bottom: 12px;
      transition: transform 0.2s;
      
      &:hover {
        transform: translateY(-2px);
      }
      
      :deep(.el-alert__content) {
        width: 100%;
        
        .layout {
          .content {
            margin-bottom: 8px;
            font-size: 14px;
            line-height: 1.6;
          }
          
          .about {
            display: flex;
            justify-content: space-between;
            font-size: 12px;
            color: #909399;
            
            .issueAuthor, .issueTime {
              display: flex;
              align-items: center;
              
              i {
                margin-right: 4px;
              }
            }
          }
        }
      }
    }
  }
  
  // 报修订单表格部分
  .repairCenter_container {
    .table-card {
      border-radius: 8px;
      overflow: hidden;
      transition: all 0.3s;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
      
      &:hover {
        box-shadow: 0 6px 24px rgba(0, 0, 0, 0.1);
      }
      
      :deep(.el-card__header) {
        background: linear-gradient(to right, #2193b0, #6dd5ed);
        padding: 15px 20px;
      }
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .title {
          color: #fff;
          font-size: 18px;
          font-weight: bold;
        }
      }
    }
    
    .order-table {
      border-radius: 4px;
      
      :deep(.el-table__header-wrapper) {
        th {
          font-weight: 600;
          color: #333;
          background-color: #f5f7fa;
        }
      }
      
      .repair-content {
        max-width: 300px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .status-tag {
        padding: 4px 12px;
        border-radius: 15px;
      }
      
      .accept-btn {
        padding: 8px 16px;
        border-radius: 4px;
        transition: all 0.2s;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 2px 10px rgba(64, 158, 255, 0.3);
        }
        
        i {
          margin-right: 4px;
        }
      }
      
      .image-container {
        display: flex;
        justify-content: center;
        flex-wrap: wrap;
        gap: 5px;
        
        .thumbnail {
          width: 40px;
          height: 40px;
          border-radius: 4px;
          object-fit: cover;
          border: 1px solid #eaeaea;
          cursor: pointer;
          transition: transform 0.2s;
          
          &:hover {
            transform: scale(1.05);
          }
        }
        
        .no-images {
          color: #909399;
          font-size: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
  }

  .pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    padding: 10px 0;
  }
}

/* 修复ResizeObserver相关问题 */
.resize-observer-fix {
  position: relative;
  overflow: hidden;
}

/* 媒体查询适配移动设备 */
@media screen and (max-width: 768px) {
  .worker-repair-center {
    .repairCenter_container {
      .table-card {
        .card-header {
          .title {
            font-size: 16px;
          }
        }
      }
      
      .order-table {
        .repair-content {
          max-width: 150px;
        }
      }
    }
  }
}
</style>